package com.heima.admin.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthorizeFilter implements GlobalFilter {
    //创建白名单
    private  static final List<String> urlList = new ArrayList<>();
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.从上下文中获取请求 和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求中的路径
        String path = request.getURI().getPath();
        //判断请求中的路径是否为白名单
        for (String url : urlList) {
            if (path.equals(url)) {
               return chain.filter(exchange);
            }
        }
        //2.获取请求头中的token
        //查看请求中是否携带token
        String token = request.getHeaders().getFirst("token");
        //如果令牌不存在
        if (StringUtils.isEmpty(token)) {
            //响应一个状态码
          /*  response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束操作
            return response.setComplete();*/
            return writeMessage(exchange,"token为空不存在");
        }
        //3.对令牌进行解析 获取令牌的请求体
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //使用工具类解析令牌的状态是否过期 -1：有效，0：有效，1：过期，2：过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            //判断令牌的状态是否过期 1 < 有效
            if (i < 1) {
                //3.1有效将用户的id 设置到请求头
                Object id = claimsBody.get("id");
                //3.2将id设置到路由的请求头
                request.mutate().header("userId",String.valueOf(id));
                //放行
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //4.token令牌无效 设置状态码 并结束响应
  /*      response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();*/
        return writeMessage(exchange,"token状态失效");
    }

    /**
     * 返回错误提示信息
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}

